﻿using UnityEngine;

/// <summary>
/// 敌人
/// </summary>
public abstract class Enemy : StateMachineComponent<System.Type>,Damageable
{
    // 敌人生命值
    public int health=1;

    public int Health{
        get{
            return this.health;
        }
        set{
            this.health=value;
        }
    }

    //定义刚体组件
    internal Rigidbody2D rig;

    protected virtual void Awake()
    {
        // 取得刚体组件对象，只执行一次
        rig = GetComponent<Rigidbody2D>();

        // 初始化状态机
        InitStateActions();
    }


    protected override void Update()
    {
        base.Update();
    }

    protected override void FixedUpdate()
    {
        base.FixedUpdate();
    }

    protected abstract void InitStateActions();

    /// <summary>
    /// 对象是否在游戏窗口内
    /// 基于当前Sprite的边界进行判断，只有Sprite全部出现在游戏窗口才会返回true
    /// </summary>
    /// <param name="expandSize">调整判断的边界大小</param>
    /// <returns></returns>
    public bool AllInViewPort(float expandSize = 0.0f)
    {
        Bounds bounds = GetComponent<Renderer>().bounds;

        Vector2 leftUpPoint = new Vector2(bounds.min.x, bounds.max.y);
        Vector2 rightUpPoint = new Vector2(bounds.max.x, bounds.max.y);
        Vector2 leftDownPoint = new Vector2(bounds.min.x, bounds.min.y);
        Vector2 rightDownPoint = new Vector2(bounds.max.x, bounds.min.y);


        return Utility.InCameraViewport(Camera.main, leftUpPoint, expandSize)
            && Utility.InCameraViewport(Camera.main, rightUpPoint, expandSize)
            && Utility.InCameraViewport(Camera.main, leftDownPoint, expandSize)
            && Utility.InCameraViewport(Camera.main, rightDownPoint, expandSize)
        ;
    }

    /// <summary>
    /// 受到伤害
    /// </summary>
    /// <param name="damageSource">伤害来源</param>
    /// <returns>造成的实际伤害</returns>
    public int Damage(GameObject damageSource,int damagePoint){
        this.Health-=damagePoint;
        if(this.Health<=0){
            this.Die();
        }
        int ret=damagePoint;
        if(this.Health<0){
            ret=this.Health+damagePoint;
        }
        return ret;
    }

    public abstract void Die();
}

/// <summary>
/// 敌人状态类的基类
/// </summary>
public abstract class EnemyStateAction : IStateAction<System.Type>
{
    // 状态上下文中的敌人对象
    protected Enemy enemy;
    // 状态类的状态值
    public System.Type State { get { return this.GetType(); } }

    /// <summary>
    /// 初始化方法
    /// </summary>
    /// <param name="enemy">敌人对象</param>
    public EnemyStateAction(Enemy enemy)
    {
        this.enemy = enemy;
    }
    
    public virtual void Enter(System.Type lastState, System.Type currentState){}
    public virtual void Exit(System.Type currentState, System.Type nextState){}
    public virtual void Update(System.Type inState, out System.Type outState){
        outState=inState;
    }
    public virtual void FixedUpdate(System.Type inState, out System.Type outState){
        outState=inState;
    }
    
}

